//
//  XKOOauthViewController.swift
//  sinawb
//
//  Created by Mars on 16/4/10.
//  Copyright © 2016年 Mars. All rights reserved.
//

import UIKit

class XKOOauthViewController: UIViewController {

    
    override func loadView() {
        super.loadView()
        view = XKOWebView
        XKOWebView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

      self.setupNavgationItem()
      self.navigationItem.title = "微博授权界面"
    
      //加载webView授权界面
        let URL:NSURL = OauthUrl()
        let request:NSURLRequest = NSURLRequest(URL: URL)
        XKOWebView.loadRequest(request)
    }
    
    
    //拼接授权登录url
    func OauthUrl()->NSURL{
    
        let urlString = OauthURL + "?client_id=" + client_id + "&redirect_uri=" + redirect_uri
    
        return NSURL(string: urlString)!
    }
    
    
    func setupNavgationItem(){
    
        var leftItm = navigationItem.leftBarButtonItem
        
        leftItm = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "oauthfill")

        leftItm?.tintColor = UIColor.orangeColor()
     
        self.navigationItem.leftBarButtonItem = leftItm
        
        var rightItem = navigationItem.rightBarButtonItem
        
        rightItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "dismiss")
        rightItem?.tintColor = UIColor.orangeColor()
        
        self.navigationItem.rightBarButtonItem = rightItem
        
    }

    

    //MARK:填充/取消按钮点击事件
    func oauthfill(){
        
        print("oauthfill")
        let js = "document.getElementById('userId').value = '18102628889';document.getElementById('passwd').value = '1122334455'"
        XKOWebView.stringByEvaluatingJavaScriptFromString(js)
    }
    
    //关闭当前控制器
    func dismiss(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //MARK:懒加载webView
    private lazy var XKOWebView : UIWebView = UIWebView()
    
    }



//设置webView代理
extension XKOOauthViewController: UIWebViewDelegate{

    //webview加载完毕
    func webViewDidFinishLoad(webView: UIWebView) {
        print("webView加载完毕")
    }
    
    //webView加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        print("webView加载失败")
    }
    
    //WebView开始加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        print("webView开始加载")
        //absoluteString 显示完整的字符串
        let url = request.URL?.absoluteString

        //判断前缀是否是回调地址的,如果不是就放行
        
        let isrecodeURL = url!.hasPrefix(requestfix)
        
        print(isrecodeURL)

        
        if !isrecodeURL{
        //如果不是回调请求的前缀,就放行
            return true
        }else{
            
            //query  是get请求?后面的东西
            let codeString = "code="
            let query = request.URL?.query
            let codebool = query!.hasPrefix(codeString)
            //如果是授权按钮,放行
            if codebool{
                
                print("授权按钮被点击了")
            
                //截取code= 后面的字符串  query!.substringFromIndex(index)  从最后面开始截取到指定位置
                let index = codeString.endIndex
                let queryStr = query!.substringFromIndex(index)
                print("-----\(queryStr)")
                
                //类型转换截取code=后面的字符串
                let  queryStrr = (query! as NSString).substringFromIndex(codeString.characters.count)
                print("-----\(queryStrr)")
            }else{
            
                dismiss()
                print("取消按钮被点击了")
            }
        
            return false
        }
        
        //Optional("http://www.baidu.com/?code=664d934150d967b1343286dd210e4249")
        //:Optional("http://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330")

}


}

